<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller;

use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
// use ImiApp\ApiServer\Common\AuthApi;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Aop\Annotation\Inject;
use ImiApp\ApiServer\Api\Model\Attachment;

use Imi\Config;
use Imi\Util\File;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemException;

use Imi\Server\Http\Message\UploadedFile;

/**
 * @Auth(name="token",nologin={"upload","upload_base64","read","delete","base64_image_content"})
 * @Controller("/common/")
 */
class Common extends ApiBase
{
    public function __construct($config = [])
    {
        $this->config = $config ?: Config::get('@app.beans.Upload');
    }

    /**
     * @Inject("ApiAttachment2Service")
     * 
     * @var ImiApp\ApiServer\Api\Service\Attachment2Service
     */
    protected $service;

    /**
     * 图片上传
     * @Action
     * @return ResponseInterface
     */
    public function upload(): ResponseInterface
    {
        //     * @Route(url="upload",method="POST")
        $upload = $this->service->pull($this->request->getUploadedFiles());
        return $upload ? $this->success('上传成功', $upload) : $this->error($this->service->getError());
    }


    /**
     * 水印图片
     * @Action
     * @return ResponseInterface
     */
    public function upload_water_image(): ResponseInterface
    {
        //     * @Route(url="upload_water_image",method="POST")
        $upload = $this->service->upload_water_image($this->request->getUploadedFiles());
        return $upload ? $this->success('上传成功', $upload) : $this->error($this->service->getError());
    }
    

    /**
     * base64上传文件
     * @param string $base64_img
     * 
     * @Action
     * @return void
     */
    public function upload_base64($base64_img)
    {
        //     * @Route(url="upload_base64",method="POST")
        // if ($this->request->isPost()) {
            // $param = $this->request->param();
            // $validate = new \think\Validate([
            //     'base64_img' => 'require',
            // ]);
            // $validate->message([
            //     'base64_img.require' => '缺少图片base64数据!',
            // ]);
            // if (!$validate->check($param)) {
            //     $this->error($validate->getError());
            // }
            if(!$base64_img)
                return $this->error('缺少图片base64数据!');
            $path = '/uploads';
            $attachment = $this->base64_image_content($base64_img, $path);
            if (!$attachment) {
                return $this->error('上传失败');
            }
            // var_dump('config',Config::get('@app.beans.Upload'));
            return $this->success('上传成功', ['url' => $attachment['url'], 'fullurl' => trim(Config::get('@app.beans.Upload')['domain'], '/') .$attachment['url']]);
        // }
    }


    private function base64_image_content($base64_image_content, $path)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $file_path = date('Ymd', time()) . "/";
            $new_file =  $path . "/" . $file_path;

            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0755, true);
            }
            var_dump($result);
            $file_name =  md5(base64_decode(str_replace($result[1], '', $base64_image_content))) . ".".$result[2];
            $new_file = $new_file .$file_name;
            $old_file = $path . "/" .$file_path.$file_name;

            $res =  file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));

            if ($res) {



                // $file = new UploadedFile($new_file,'image/jpeg',$new_file,filesize($new_file),0);
                // $data = (new \ImiApp\ImiServer\Service\Upload)->pull($file);
                // var_dump('data',$data);
                $getimagesize = getimagesize($new_file);
                // $img =   imagecreatefromjpeg($new_file);
                $params = array(
                    // 'admin_id'    => (int)session('admin.id'),
                    'user_id'     => $this->auth->id??0,
                    'store_id'=>$this->auth->id??0,
                    'filename'    => $file_name,
                    'filesize'    => filesize($new_file),
                    // 'imagewidth'  => imagesx($img),
                    // 'imageheight' => imagesy($img),
                    'imagewidth'  => $getimagesize[0],
                    'imageheight' => $getimagesize[1],
                    'imagetype'   => $result[2],
                    'imageframes' => 0,
                    'mimetype'    => 'image/'.$result[2],
                    'url'         => $path . "/" . $file_path . $file_name,
                    'uploadtime'  => time(),
                    'storage'     => 'local',
                    'sha1'        => hash_file('sha1', $new_file),
                    'extparam'    => '',
                    'updatetime' => time(),
                    'createtime' => time(),
              
                );
                
                $attachment = new Attachment();
                $res = $attachment::query()->where('sha1','=',hash_file('sha1', $new_file))->count();
                if(!$res){
                    $attachment->insert($params);
                }

                // \think\Hook::listen("upload_after", $attachment);
                return $params;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }



    /**
     * @Action
     * @Route("parents")
     * @return ResponseInterface
     */
    public function parents(): ResponseInterface
    {
        return $this->success(null, $this->service->getParents());
    }

    /**
     * @Action
     * @Route("read")
     * @return ResponseInterface
     */
    public function read(): ResponseInterface
    {
        return $this->success(null, $this->service->read());
    }

    /**
     * @Action
     * @Route("delete")
     * @return ResponseInterface
     */
    public function delete(): ResponseInterface
    {
        return $this->service->delete() ? $this->success('删除成功') : $this->error($this->service->getError());
    }
}